package cn.gov.pbc.tims.controller;

import java.io.IOException;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import cn.gov.pbc.tims.entity.City;
import cn.gov.pbc.tims.entity.Jginfo;
import cn.gov.pbc.tims.entity.User;
import cn.gov.pbc.tims.service.CommonService;
import cn.gov.pbc.tims.service.DictService;
import cn.gov.pbc.tims.util.Operator;
import cn.gov.pbc.tims.util.PageData;
import cn.gov.pbc.tims.util.Result;
  

@Controller  
@RequestMapping("/jg")  
public class JgAllController {  
  
    @Autowired  
    private CommonService commonService;
    @Autowired 
    private DictService systemService;
    @Autowired
    private Operator operator;    
	@Autowired 
	private ObjectMapper objectMapper;

    @Autowired
	private SessionFactory sessionFactory;

	private Session getCurrentSession() {
		return this.sessionFactory.getCurrentSession();
	}

	@Autowired
	private PageData grid_data;
    
 
    
    @RequestMapping("/getJgAll") 
    public @ResponseBody PageData getJgAll(Integer page, Integer rows, String filter) {
    	User oper=operator.getUser();
    	//System.out.println("page="+page+"page size="+rows+"   filter="+filter);
    	//二级缓存，后面加条件，只取一部分结果
    	if(filter == null) filter="";
    	
		Query<Jginfo> q = this.getCurrentSession().createQuery("from Jginfo where c1Id='A'  "+filter, Jginfo.class).setCacheable(true);
		q.setFirstResult((page-1)*rows).setMaxResults(rows);
		List<Jginfo> hbJginfos = q.getResultList();
		
		//取出全部的条目数，为了计算表格页数
		Query<Long> q2 = this.getCurrentSession().createQuery("select count(1) from HbJginfo where c1Id='A'  "+filter, Long.class).setCacheable(true);
		Long count = q2.getSingleResult();
		
		grid_data.setValue(count.intValue(), hbJginfos);
		return grid_data;
    }  
    
    
    @RequestMapping("/deletebyid")  
	public @ResponseBody Result  login(int iid){  
    	Result result=new Result();
    	//System.out.println("传来的iid=="+iid);
		
    	commonService.delete(iid);
    	
		result.setValue(0, "删除成功");
		
		return result;  
	}  
    
    @RequestMapping("savejg")
	public @ResponseBody Result savejg(Jginfo op){
    	Result result=new Result();
		//System.out.println(op.getJgName());
		
    		op.setC1Id('A');
    		op.setC1Name("货币当局");
    		op.setC2Id('1');
    		op.setC2Name("中国人民银行");
    		op.setC3Id("0001");
    		op.setC3Name("中国人民银行");
    		
    		
    		//根据县id设置全的省市县信息
    		if(op.getJgCountyId()==null||op.getJgCountyId().equals(""))
    		{
    			result.setValue(0, "请输入所在地市信息！");
    			return result;
    		}
    		String hql="from City where code=? ";
    		List <City> citys = systemService.findHql(hql,new Object[]{Integer.valueOf(op.getJgCountyId()).intValue()});
    		op.setJgCountyName(citys.get(0).getName());
    		op.setJgProvId("370000");
    		op.setJgProvName("山东省");
    		hql="from City where code=? ";
    		List <City> citys2 = systemService.findHql(hql,new Object[]{citys.get(0).getUpCode()});
    		op.setJgCityId(Integer.valueOf(citys2.get(0).getCode()).toString());
    		op.setJgCityName(citys2.get(0).getName());
    		
    	
    	
    	try {
    		commonService.saveOrUpdate(op);
    		result.setValue(0, "保存成功！");
		} catch (Exception e) {
			result.setValue(0, "该机构代码已存在或格式错误，请重新录入！");
		}
		
		

		return result;		
	}
 
    
    
    //获取地市的tree
    private List<City> getChildren(Integer id){
 		Query<City> q = this.getCurrentSession().createQuery("from City where upCode= '"+id+"'", City.class).setCacheable(true);
		List<City> citys = q.getResultList();
		return citys;
 	}
 	private boolean hasChildren(Integer id){
 		return getChildren(id).size()>0;
 	}
 	
 	
 		@RequestMapping(value="getallcity",produces=MediaType.APPLICATION_JSON_VALUE)
 		public @ResponseBody ArrayNode getallcity(Integer id) throws JsonProcessingException, IOException{
 			ArrayNode jsonArray=objectMapper.createArrayNode();
 			//if(id==null) id=370000;
 			for(City city : getChildren(id)){
 				ObjectNode jsonObject=objectMapper.createObjectNode();
 				int id0 =  city.getCode();
 				jsonObject.set("id",objectMapper.convertValue(id0,JsonNode.class));
 				jsonObject.set("text",objectMapper.convertValue(city.getName(),JsonNode.class));
 				jsonObject.set("state",objectMapper.convertValue(hasChildren(id0) ? "closed" : "open",JsonNode.class));
 				if(hasChildren(id0)){
 					jsonObject.set("children", getallcity(id0));
 				}
 				jsonArray.add(jsonObject);
 			}
 			return jsonArray;
 		}
 		

}  
